package com.qfedu.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 作者：刘随阳
 * 时间: 2021/8/13 22:48
 * 描述：神光照耀,太白成瑞。六丙来迎,百福悠归
 */
@Component
@ServerEndpoint("/wx/websoket/{orderId}")
public class WebSocketServer {

    public static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     *   前端发送请求时 调用的方法
     */
    @OnOpen
    public void open(@PathParam("orderId") String orderId,Session session){
        System.out.println(orderId+":建立连接");
        sessionMap.put(orderId,session);
    }

    /**
     *   前端页面关闭时 调用的方法
     */
    @OnClose
    public void close(@PathParam("orderId") String orderId,Session session){
        System.out.println(orderId+":连接关闭");
        sessionMap.remove(orderId);
    }

    public static void sendmsg(String orderId,String msg){
        Session session = sessionMap.get(orderId);
        try {
            session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
